package com.sakura.system.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.sakura.system.entity.gld.User;
import com.sakura.system.service.impl.gldimpl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * gld
 * 2024-03-4
 * token工具类
 */

@Component
public class JwtTokenUtils {

    private static UserServiceImpl staticService;
//    日志，可以在下面调用他打印信息：
    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);

    @Resource
    private UserServiceImpl service;

//    项目初始化会执行该方法
    @PostConstruct
    public void setUserService(){
        staticService = service;
    }
    /**
     * 生成token
     */
    public static String genToken(String userId, String sign){
        return JWT.create().withAudience(userId) // 将id保存到token里面，作为载核
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign));
    }

    /**
     * 获取当前用户信息
     */
    public static User getCurrentUser(){
        String token = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("token");
            if(StrUtil.isBlank(token)){
                token = request.getParameter("token");
            }
            if (StrUtil.isBlank(token)){
                log.info("获取当前登陆token失败,token={}",token);
                return null;
            }
            // 解析token,获取用户id
            String id = JWT.decode(token).getAudience().get(0);
//            return staticService.fibdBySearch(Integer.valueOf(id));
            return staticService.fibdByById(Integer.valueOf(id));
        } catch (Exception e){
            log.error("获取当前用户登陆信息失败,token={}",token, e);
            return null;
        }
    }



}
